package com.onpositive.wiki2.whole.model;

import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Arrays;

public class SimpleRelationStore {

	protected DataOutputStream stream;

	protected ContentAccess cs;

	public SimpleRelationStore(ContentAccess cs, DataOutputStream q) {
		super();
		this.cs = cs;
		this.stream = q;
	}

	public void encode(String from, String child, Integer m, boolean relation,
			boolean isUpper) throws IOException {
		
		child=child.toLowerCase();
		if (child.equals("ships")){
			System.out.println(child);
		}
		from=from.toLowerCase().replace(' ', '_');
		int id = id(from);
		if (m == null || m < 0) {
			throw new RuntimeException();
		}
		if (relation){
			String title = cs.getTitle(m);
			title=title.toLowerCase().replace(' ', '_');
			if (title.startsWith("category:")){
				title=title.substring("category:".length());
			}
			m=id(title);
		}
		
//		
//		if (relation) {
//			int size = cs.tb.size();
//			if (m < size) {
//				String title = cs.getTitle(m);
//				if (!title.equalsIgnoreCase(child)) {
//					if (title.startsWith("Category:")) {
//						title = title.substring("Category:".length());
//						if (!title.equalsIgnoreCase(child)) {
//							child = child.replace("\\'", "'");
//							child = child.replace("\\\"", "\"");
//							if (!title.equalsIgnoreCase(child)) {
//								String[] split = child.split("\\\\n");
//								if (split.length == 2) {
//									if (!title.equalsIgnoreCase(split[1])) {
//										m = id(child);
//									}									
//								}								
//							}
//							
//						}
//						else{
//							m = id(title);							
//						}
//					}
//				}
//			} else {
//				m = id(child);
//			}
//		}
		String title = cs.getTitle(id);
		if (!title.equals(from)) {
			throw new RuntimeException();
		}
		stream.writeInt(id);
		stream.writeInt(m);
	}

	protected int qqq(String string) {
		String to;
		int is1;
		StringBuilder ml = new StringBuilder();
		for (int a = 0; a < string.length(); a++) {
			if (a == 0) {
				ml.append(Character.toUpperCase(string.charAt(a)));
				continue;
			}
			if (string.charAt(a - 1) == '_') {
				ml.append(Character.toUpperCase(string.charAt(a)));
				continue;
			}
			ml.append(string.charAt(a));
		}
		to = ml.toString();
		is1 = qid(to);
		if (is1 == -1) {
			String sp = to.replace('_', ' ');
			is1 = qid(sp);
			if (is1 == -1) {
				is1 = qid(Character.toUpperCase(sp.charAt(0))
						+ sp.substring(1).toLowerCase());
			}
		}
		if (is1 == -1) {
			is1 = qid(Character.toUpperCase(to.charAt(0))
					+ to.substring(1).toLowerCase());
		}
		return is1;
	}

	protected int qid(String to) {
		return cs.tb.id(to);
	}

	protected int id(String from) {
		int id = qid(from);
		if (id == -1) {
			id = cs.tb.allocateId(from);
		}
		return id;
	}

	static class LinkStore {

	}

	void foo(int[] a) {
		Arrays.sort(a);
	}

}
